﻿/*
 * log.h
 *
 *  Created on: 2017年4月9日
 *      Author: XJY
 */

#ifndef __M_LOG_H_
#define __M_LOG_H_

#include <stdio.h>
#include <stdlib.h> //errno
#include <errno.h>
#include <time.h>
#include <sys/timeb.h>
#include <string.h> //memset

#define LOGON (1) //log 输出开关

#define DTIME_LEN   (22) //19700101|08:00:22.372
extern FILE * G_LOG_OUT__;
extern int G_LOG_DETAIL;

#if defined(LOGON)
	#define logdebug(x, ...) \
		{ \
			char dtime[DTIME_LEN]; \
			logGetDateTime( dtime, sizeof(dtime) );\
			if(G_LOG_DETAIL != 0) { \
				logprint( "[%s] [DEBUG] %s(line:%d)(func:%s): " x, dtime, \
						__FILE__, __LINE__, __FUNCTION__, ## __VA_ARGS__); \
			} else {\
				logprint("" x, ## __VA_ARGS__); \
			} \
		}
	#define loginfo(x, ...) \
		{ \
			char dtime[DTIME_LEN]; \
			logGetDateTime( dtime, sizeof(dtime) );\
			if(G_LOG_DETAIL != 0) { \
				logprint("[%s] [INFO] %s(line:%d)(func:%s): " x, dtime, \
						__FILE__, __LINE__, __FUNCTION__, ## __VA_ARGS__); \
			} else { \
				logprint("" x, ## __VA_ARGS__); \
			} \
		}
	#define logprint(x, ...) \
		{ \
			fprintf(G_LOG_OUT__, "" x, ## __VA_ARGS__);\
		}
#else
	#define logdebug(x, ...)
	#define loginfo(x, ...)
	#define logprint(x,...)
#endif

#define logerr(x, ...) \
	{ \
		char dtime[DTIME_LEN]; \
		logGetDateTime( dtime, sizeof(dtime) );\
		if(G_LOG_DETAIL != 0) { \
			fprintf(stderr, "[%s] [ERROR] %s(line:%d)(func:%s): " x, dtime, \
				__FILE__, __LINE__, __FUNCTION__, ## __VA_ARGS__); \
		} else { \
			logprint("[ERROR]" x, ## __VA_ARGS__); \
		} \
		if(G_LOG_OUT__ != stdout && G_LOG_OUT__ != stderr && G_LOG_OUT__ != stdin){ \
			if(G_LOG_DETAIL != 0) { \
				logprint("[%s] [ERROR] %s(line:%d)(func:%s): " x, dtime, \
						__FILE__, __LINE__, __FUNCTION__, ## __VA_ARGS__); \
			} else { \
				logprint("" x, ## __VA_ARGS__); \
			} \
		} \
	}

void setLogOut(char *filename);
void setLogDetail(int mode);
int closeLogOut();
int closeLogOut2File();
int logGetDateTime(char *dtime, int len);
void loghex(unsigned char *data, int datalen, const char *msg);

#endif /* __M_LOG_H_ */
